package com.example.crawler.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.client.methods.CloseableHttpResponse;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class SendHttpsRequestUtil {

    public static String post(String path, Map<String, String> parameters) throws IOException, GeneralSecurityException {
        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(path);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setRequestProperty("User-Agent", "Mozilla/4.76");
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setDoInput(true);// 打开输入流，以便从服务器获取数据
        httpsConn.setDoOutput(true);// 打开输出流，以便向服务器提交数据
        if (parameters != null) {
            url = new URL(url.toString() + buildGetParameterString(parameters));
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
        String line;
        StringBuffer rt = new StringBuffer();
        while ((line = in.readLine()) != null) {
            rt.append(line);
        }
        return rt.toString();
    }

    public static boolean postPicture(String filePath,String imageUrl) throws IOException, GeneralSecurityException {
        // 截取图片的名称
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/"));
        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext 对象中得到 SSLSocketFactory 对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(filePath);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setRequestProperty("User-Agent", "Mozilla/4.76");
        httpsConn.setSSLSocketFactory(ssf);
        InputStream is = httpsConn.getInputStream();
        // 创建文件，并设置默认文件名
        File file = new File(filePath + fileName);
        FileOutputStream out = new FileOutputStream(file);
        int i = 0;
        while ((i = is.read()) != -1) {
            out.write(i);
        }
        is.close();
        out.close();
        return true;
    }

    private static String buildGetParameterString(Map<String, String> parameters) {
        String getParameterString = "";
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            if (param.getValue() == null) {
                continue;
            }
            getParameterString += (getParameterString.length() < 1) ? ("?") : ("&");
            getParameterString += param.getKey() + "=" + param.getValue();
        }
        return (getParameterString);
    }


}
